//
//  ReversiAlphaBetaVirtualPlayer.m
//  Reversi
//
//  Created by 成瀬 龍人 on 2/19/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ReversiAlphaBetaVirtualPlayer.h"

int staticValue(ReversiBoard* board, ReversiStone stone){
	return [board numberOf:stone] - [board numberOf:ReversiStone2Negative(stone)];
}

int alphabeta(ReversiBoard* board, ReversiStone stone, int depth, int alpha, int beta, int signe){
	//終了条件
	if(0 == depth || [board isGameOver]){
		return signe * staticValue(board, stone);
	}
	
	NSArray* positions = [board allocatablePositions:ReversiStone2View(stone, signe)];
	//パスの場合
	if(0 == [positions count]){
		return alphabeta(board, stone, depth - 1, -1 * beta, -1 * alpha, -1 * signe);
	}
	//探索
	for(ReversiBoardPosition* pos in positions){
		ReversiBoard* nextBoard = [board copy];
		[nextBoard putAndChange:ReversiStone2View(stone, signe):pos];
		alpha = MAX(alpha, -1 * alphabeta(nextBoard, stone, depth - 1, -1 * beta, -1 * alpha, -1 * signe));
		if(alpha >= beta){
			return alpha;
		}
	}
	return alpha;
}

@implementation ReversiAlphaBetaVirtualPlayer

- (id)initWithBundle:(NSBundle*)bundle{
	[super init];
	return self;
}

- (ReversiBoardPosition*)nextHand:(ReversiStone)aStone:(ReversiBoard*)aBoard{
	NSArray* positions = [aBoard allocatablePositions:aStone];
	ReversiBoardPosition* ret = nil;
	int max = INT_MIN;
	for(ReversiBoardPosition* pos in positions){
		ReversiBoard* nextBoard = [aBoard copy];
		[nextBoard putAndChange:aStone:pos];
		int val = -1 * alphabeta(nextBoard, aStone, 5, INT_MIN + 1, INT_MAX, -1);
		if(val > max){
			max = val;
			ret = pos;
		}
	}
	return ret;
}

- (BOOL)haveConfigWindow{
	return NO;
}

- (void)openConfigWindow{
}

- (void)setUpPlayer{
}

- (NSString*)name{
	return @"AlphaBeta Player";
}

- (NSString*)description{
	return @"AlphaBeta Method";
}

@end
